from flask import Flask, request, jsonify, send_file, render_template
import os
from pathlib import Path
from word2md import Word2MD
import zipfile

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/upload', methods=['POST'])
def upload_file():
    try:
        # 保存上传的文件
        # 保存上传的文件
        uploaded_file = request.files.get('word-file')
        if not uploaded_file or not uploaded_file.filename:
            return jsonify({'error': 'No file or filename provided'}), 400
        word_path = Path('words_in') / uploaded_file.filename
        word_path.parent.mkdir(parents=True, exist_ok=True)
        uploaded_file.save(word_path)

        # 执行转换
        converter = Word2MD(word_path)
        converter.run()

        # 压缩输出文件
        output_dir = Path(converter.output_dir)
        zip_filename = output_dir / f'{word_path.stem}.zip'
        with zipfile.ZipFile(zip_filename, 'w') as zipf:
            # 仅压缩md文件和images文件夹
            for file in output_dir.glob('*.md'):
                zipf.write(file, file.relative_to(output_dir.parent))
            images_dir = output_dir / 'images'
            if images_dir.exists():
                for image_file in images_dir.rglob('*'):
                    zipf.write(image_file, image_file.relative_to(output_dir.parent))

        return jsonify({'markdown_file': str(converter.md_path), 'zip_file': str(zip_filename)}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/download')
def download_file():
    file_path = request.args.get('file')
    if file_path and Path(file_path).exists():
        return send_file(file_path, as_attachment=True)
    return jsonify({'error': 'File not found'}), 404

@app.route('/download2')
def download2_file():
    file_path = request.args.get('file')
    if file_path and Path(file_path).exists() and file_path.endswith('.md'):
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
        return jsonify({'content': content}), 200
    return jsonify({'error': 'File not found or not an MD file'}), 404

@app.route('/convert', methods=['POST'])
def convert_word_to_md():
    try:
        # 尝试获取 JSON 数据
        data = request.get_json(silent=True)
        
        if data is None:
            # 如果获取 JSON 失败，尝试从表单数据中获取
            data = request.form.to_dict()
            if not data:
                # 如果表单数据也没有，尝试从请求体中解析
                data = request.values.to_dict()
            print(f"Received data from form or values: {data}")
        else:
            print(f"Received data: {data}")

        word_path = data.get('word_path')
        output_dir = data.get('output_dir', 'outputs')

        if not word_path:
            return jsonify({'error': 'word_path is required'}), 400

        # 转换路径为Path对象
        word_path = Path(word_path)

        # 执行转换
        converter = Word2MD(word_path, output_dir)
        converter.run()

        return jsonify({'message': 'Conversion successful',
                        'output_directory': str(converter.output_dir),
                        'markdown_file': str(converter.md_path)}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=6687)
